package com.example.base.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.base.Utils.CookieJarManager;
import com.example.base.Utils.SpUtil;
import com.example.base.activity.LoginActivity;
import com.example.base.bean.Loginone;
import com.example.base.R;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static androidx.constraintlayout.motion.utils.Oscillator.TAG;


public class LoginFragment extends Fragment {

  private String mParam1;
  private String mParam2;
  private LinearLayout linearLayout;
  private Context context;
  private EditText name, password;
  private Button login;
  private String username;
  private String pwd;
  private int ResultCode = 1;
  private CookieJarManager cookieJarManager;

  public LoginFragment() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    View inflate = inflater.inflate(R.layout.fragment_login, container, false);
    initView(inflate);
    initListener();
    return inflate;
  }

  private void initView(View inflate) {
    linearLayout = inflate.findViewById(R.id.linear_register);
    name = inflate.findViewById(R.id.ed_name_login);
    password = inflate.findViewById(R.id.ed_password_login);
    login = inflate.findViewById(R.id.btn_login);
    context = getContext();
  }

  private void initListener() {
    linearLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        final LoginActivity loginActivity = (LoginActivity) getActivity();
        loginActivity.chageViewPager(1);
      }
    });
    login.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            username = name.getText().toString();
            pwd = password.getText().toString();
            OkHttpClient.Builder client = new OkHttpClient.Builder();
            CookieJarManager cm = new CookieJarManager();
            client.cookieJar(cm);
            RequestBody body = new FormBody.Builder()
                .add("username", username)
                .add("password", pwd)
                .build();
            Request request = new Request.Builder()
                .url("https://www.wanandroid.com/user/login")
                .post(body)
                .build();
            Call call = client.build().newCall(request);
            // 同步或异步请求
            call.enqueue(new Callback() {
              @Override
              public void onFailure(@NotNull Call call, @NotNull IOException e) {

              }

              @Override
              public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                  List<Cookie> cookie = cm.getMcookies();
                  for (int j = 1; j < cookie.size(); j++) {
                    String key = cookie.get(j).toString().split("=")[0];
                    String value = cookie.get(j).toString().split(";")[0];
//                                        SharedPreferences sp = getActivity().getSharedPreferences("cookies", Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString(key, value);
//                                        edit.commit();
                    SpUtil.getInstance(getContext()).saveState(key, value);
                  }
                  Gson gson = new Gson();
                  String data = response.body().string();
                  Log.i(TAG, data);
                  Loginone loginone = gson.fromJson(data, Loginone.class);
                  if (loginone.getErrorCode() == 0) {
                    getActivity().runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                        Toast.makeText(context, "登陆成功", Toast.LENGTH_LONG).show();
                        SharedPreferences sp = getActivity().getSharedPreferences("username", Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        String user = loginone.getData().getUsername();
                        edit.putString("user", user);
                        edit.commit();
                        Intent intent = new Intent();
                        intent.putExtra("result", username);
                        getActivity().setResult(RESULT_OK, intent);
                        //关闭Activity
                        getActivity().finish();
                      }
                    });
                  } else {
                    getActivity().runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                        Toast.makeText(context, "账号密码不匹配", Toast.LENGTH_SHORT).show();
                      }
                    });
                  }

                }
              }
            });

          }
        });
      }
    });

  }

}